import babel from "@rollup/plugin-babel";
import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";

import typescript from "@rollup/plugin-typescript";

import { terser } from "rollup-plugin-terser";
import postcss from "rollup-plugin-postcss";

import json from "@rollup/plugin-json"; // 将json转成 es模块，利于 Tree-Shaking
import filesize from "rollup-plugin-filesize"; //打包显示文件大小

import serve from "rollup-plugin-serve";
import livereload from "rollup-plugin-livereload";

import pkg from "./package.json";

function getOutput() {
  const format = ["amd", "es", "iife", "cjs", "umd"];
  return format.map((f) => {
    return {
      file: `dist/bound.${f}.js`,
      format: f, // amd es iife cjs umd
      name: (f === "iife" || f === "umd") && "ly", // 当 format 为 iife 和 umd 时必须提供，将作为全局变量挂在 window 下
      banner: "/* my-library version " + pkg.version + " */",
      footer: "/* follow me on Twitter! @" + pkg.author + "*/",
      globals: {
        lodash: "_", // 告诉 rollup 全局变量 _ 即是 lodash
        jquery: "$", // 告诉 rollup 全局变量 $ 即是 jquery
      },
    };
  });
}

export default {
  input: "src/main.ts",
  output: getOutput(),
  external: ["lodash", "jquery"],
  plugins: [
    // babel 解析 ES6+ 的高级语法
    babel({
      // exclude: "node_modules/**",
      include: "src/**",
      babelHelpers: "bundled",
    }),
    resolve(), // 告诉 rollup 如何查找第三方库
    commonjs(), // 支持 commonjs 格式的模块导入
    typescript(), // 解析 ts

    process.env.NODE_ENV === "development" ? null : terser(), // 压缩 js
    postcss(), // 压缩 css
    json(),
    filesize(),
    process.env.NODE_ENV === "development"
      ? serve({
          open: true,
          openPage: "/public/index.html",
          port: 3000,
          contentBase: "",
        })
      : null,
    process.env.NODE_ENV === "development"
      ? livereload(resolve(__dirname, "dist"))
      : null, // 启动重载，并且监听dist目录
  ],
};
